package logic

import (
	"encoding/json"
	"fmt"
	"math"
	"strconv"
	"time"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gtime"
)

type PolygonLogic struct {
}

type TradeResult struct { // 定义交易结果结构体
	Status  string `json:"status"` // 状态字段
	Message string `json:"message"`
	Result  []struct {
		TimeStamp    string `json:"timeStamp"`
		Value        string `json:"value"`
		TokenDecimal string `json:"tokenDecimal"`
	} `json:"result"`
}

var usdtPosApiUri = "https://api.polygonscan.com/api"
var usdtPosContractId = "0xc2132D05D31c914a87C6611C10748AEb04B58e8F"

func (p *PolygonLogic) MatchTrade(wallet string, amount float64, createdAt *gtime.Time) bool {
	result, err := p.GetTradeList(wallet)

	if err != nil {
		fmt.Println("GetTradeList:", result.Message)
		return false
	}

	// 提取交易时间和金额
	for _, trade := range result.Result {
		tradeTimeStamp, err := strconv.ParseInt(trade.TimeStamp, 10, 64)
		if err != nil {
			fmt.Println("时间戳转换错误:", err)
			continue
		}
		tradeTime := time.Unix(tradeTimeStamp, 0)

		value, err := strconv.ParseFloat(trade.Value, 64)
		if err != nil {
			fmt.Println("金额转换错误:", err)
			continue
		}
		tokenDecimal, err := strconv.Atoi(trade.TokenDecimal)

		if err != nil {
			fmt.Println("TokenDecimal转换错误:", err)
			continue
		}
		convertedValue := value / math.Pow(10, float64(tokenDecimal))
		if convertedValue == amount && tradeTime.Sub(createdAt.Time) <= 30*time.Minute {
			return true
		}
	}
	return false
}

// 获取转账列表
func (p *PolygonLogic) GetTradeList(address string) (result *TradeResult, err error) {
	apikey := g.Cfg().MustGet(gctx.New(), "polygon.apikey").String()
	response, _ := g.Client().Get(
		gctx.New(),
		usdtPosApiUri,
		g.Map{
			"module":           "account",
			"action":           "tokentx",
			"address":          address,
			"contract_address": usdtPosContractId,
			"sort":             "desc",
			"offset":           10,
			"page":             1,
			"apikey":           apikey,
		},
	)
	result = &TradeResult{}
	err = json.Unmarshal(response.ReadAll(), &result)
	return
}
